import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Spin, message } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import React, { PureComponent } from 'react';

import 'moment/locale/zh-cn';
import { convertDirection } from '@/src/utils/commonFunc';

import myStyle from './index.less';
import MyModal from './myModal';

import { DATA_ENTRY, AdvancedSearch, ModalC, TableC, ContentPackage } from '../../../comps';
import colors from '../../../css/colors';

const dateFormat = 'YYYY-MM-DD';

@connect(({ limitAlarmqueryM, loading, globalM }) => ({
  limitAlarmqueryM,
  loading,
  globalM,
}))
@Form.create()
export default class LimitAlarmquery extends PureComponent {
  state = {
    visible: false, // 模态框显示与否
    modalData: {}, // 详情页数据
    searchForm: {
      startDate: moment().format(dateFormat), // 初始化开始日期结束日期
      endDate: moment().format(dateFormat),
    }, // 搜索条件
    timeOutGap: 500,
    sortedInfo: null, // 排序信息
    currentPage: 1, // 当前页码
    numInPage: 10, // 每页数量
    isReset: false, // 是否点击重置
  };

  componentDidMount() {
    this.queryTableList();
    this.riskSearch(); // 查询限额信息下拉列表
  }

  componentWillUnmount() {
    // 离开前清除models数据
    this.props.dispatch({
      type: 'limitAlarmqueryM/save',
      payload: {
        selectData: [],
        tableDataObj: {},
      },
    });
    this.setState({
      isReset: false,
    });
  }

  // eslint-disable-next-line react/no-unused-class-component-methods
  showValue = (key, dictMap, value) => {
    const values = dictMap[key] || [];
    if (!values) return '';
    let text = '';
    values.forEach((item) => {
      if (item.code === value) text = item.value;
    });
    return text;
  };

  // 查询表格数据
  queryTableList = () => {
    const { dispatch } = this.props;
    const { searchForm, numInPage, currentPage, isReset } = this.state;
    const sortedInfo = this.state.sortedInfo ? this.state.sortedInfo : {};
    if (isReset) {
      message.warning('您已重置查询字段，请设置条件后执行查询');
      return;
    }
    if (Object.keys(sortedInfo).length && sortedInfo.columnKey != 'createDateTime') return; // 阻止非排序列调用
    dispatch({
      type: 'limitAlarmqueryM/queryWaringList',
      payload: {
        ...searchForm,
        currentPage,
        numInPage,
        sortItem: sortedInfo.columnKey || '',
        sortType: sortedInfo.order || '',
      },
    });
  };

  // 表格排序改变调用
  handleTableChange = (pagination, filter, sorter) => {
    const { current, pageSize } = pagination;
    this.setState(
      {
        currentPage: current,
        numInPage: pageSize,
        sortedInfo: sorter,
      },
      () => {
        this.queryTableList();
      },
    );
  };

  // 展示表格
  showTable = () => {
    const {
      loading,
      globalM: { dataDictionary },
      limitAlarmqueryM: {
        tableDataObj: { columns = [], dataSource = [], pageInfo = {} },
      },
    } = this.props;
    const { currentPage, numInPage } = this.state;
    let { sortedInfo } = this.state;
    sortedInfo = sortedInfo || {};
    columns.map((item) => {
      if (item.key == 'increasingSequence') {
        item.width = 320;
        item.render = (text, record) => <a onClick={() => this.showInfo(record)}>{text}</a>;
      }
      if (item.key == 'alarmLimit' || item.key == 'prohibitedLimit' || item.key == 'calcValue' || item.key == 'orderQty') {
        item.width = 120;
        item.type = 'number';
      }
      if (item.key == 'price' || item.key == 'money' || item.key == 'fullPrice') {
        item.width = 120;
        item.align = 'right';
      }
      if (item.key == 'createDateTime') {
        item.width = 160;
        item.sorter = true;
        item.sortOrder = sortedInfo.columnKey === item.key && sortedInfo.order;
      }
      if (item.key == 'ruleDesc') {
        item.width = 120;
        item.render = (text) => {
          let str = text;
          if (text && text.length > 20) {
            str = `${text.substring(0, 20)}...`;
          }
          return <span title={text}>{str}</span>;
        };
      }
      if (item.key == 'controlMethod') {
        // 控制方式
        item.width = 120;
        item.render = (text) => {
          if (text) {
            return <span>{text == 1 ? '单产品控制' : '多产品控制'}</span>;
          }
          return <span>{text}</span>;
        };
      }
      if (item.key == 'controlLay') {
        // 控制层次
        item.width = 100;

        item.render = (text) => {
          if (text) {
            return <span>{text == 2 ? '产品' : ''}</span>;
          }
          return <span>{text}</span>;
        };
      }
      if (item.key == 'ruleWarnType') {
        // 警告级别
        item.width = 90;
        item.render = (text) => (text == '禁止' ? <span style={{ color: colors.debtAndProfit.text[0] }}>{text}</span> : <span>{text}</span>);
      }
      if (item.key == 'orderSide') {
        // 交易方向
        item.width = 80;
        item.render = (text, record) => convertDirection(record.type, text, dataDictionary) || '--';
      }
      if (item.key == 'portfolioRootName' || item.key == 'portfolioName' || item.key == 'tradingName') {
        // 交易方向
        item.width = 180;
      }
      if (item.key == 'tradingCode' || item.key == 'exchangeCode') {
        // 交易方向
        item.width = 120;
      }
    });

    return (
      <div>
        <Spin spinning={loading.effects['limitAlarmqueryM/queryWaringList'] == true}>
          <TableC
            columns={columns}
            dataSource={dataSource}
            onChange={this.handleTableChange}
            current={currentPage}
            total={pageInfo.total || 0}
            pageSize={numInPage}
            scroll={{ x: 'max-content' }}
            selfScrollY
            rowKey='increasingSequence'
          />
        </Spin>
      </div>
    );
  };

  // 查询详情页信息 弹出模态框
  showInfo = (e) => {
    const {
      globalM: { dataDictionary },
    } = this.props;
    const str = convertDirection(e.type, e.orderSide, dataDictionary); // 转换交易方向为文字
    const tempObj = JSON.parse(JSON.stringify(e));
    tempObj.orderSide = str;
    this.setState({
      visible: true,
      record: tempObj,
      timeStamp: new Date().getTime(),
    });
  };

  // 限额信息模糊搜索
  riskSearch = (e) => {
    const tenant = localStorage.getItem('antd-pro-tenant');
    const { dispatch } = this.props;

    dispatch({
      type: 'limitAlarmqueryM/getSelectData',
      payload: {
        pageNumber: 1,
        pageSize: 999,
        ruleDesc: e,
        tenant,
      },
    });
  };

  showModal = () => {
    const props = {
      visible: this.state.visible,
      onOk: () => {
        this.setState({ visible: false });
      },
      onCancel: () => {
        this.setState({ visible: false });
      },
      title: '触警详情',
      className: 'limitAramDetail',
      footer: null,
      height: 500, // 内容区域的高度
    };
    return (
      <div>
        <ModalC {...props}>
          <MyModal record={this.state.record} timeStamp={this.state.timeStamp} modalData={this.state.modalData} />
        </ModalC>
      </div>
    );
  };

  render() {
    const {
      limitAlarmqueryM: { selectData },
    } = this.props;
    const searchProps = {
      dataSource: [
        {
          dataIndex: ['startDate', 'endDate'],
          title: '日期区间',
          type: DATA_ENTRY.RANGEDATE,
          initialValue: [moment(), moment()],
        },
        {
          dataIndex: 'limitInfoIds',
          title: '限额信息',
          type: DATA_ENTRY.SELECT,
          dataSource: selectData,
          isMultiple: true,
          allowClear: true,
          optionTitle: true,
          // onSearch: (e) => { this.riskSearch(e) },
          filterOption: (
            input,
            option, // 模糊搜索value 和 title
          ) =>
            // eslint-disable-next-line implicit-arrow-linebreak
            option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0 || option.props.value.toLowerCase().indexOf(input.toLowerCase()) >= 0,
        },
        {
          dataIndex: 'productList',
          title: '产品',
          type: DATA_ENTRY.PRODUCTLIST,
          multiple: true,
        },
      ],
      onQuery: (e) => {
        e.startDate = e.startDate.format(dateFormat); // 转换下时间格式
        e.endDate = e.endDate.format(dateFormat); // 转换下时间格式
        this.setState(
          {
            searchForm: e,
            currentPage: 1,
            isReset: false,
          },
          () => {
            this.queryTableList(); // 点击查询按钮
          },
        );
      },
      onClear: () => {
        // 点击重置按钮
        this.setState({
          searchForm: {
            startDate: moment().format(dateFormat),
            endDate: moment().format(dateFormat),
          },
          sortedInfo: null,
          isReset: true, // 开启重置后 页面不再向后台请求
        });
      },
    };
    return (
      <ContentPackage
        title='限额触警查询'
        contentHtml={
          <div>
            <div className={myStyle.limitAlarmquery}>
              <div className={myStyle.cardBody}>
                <AdvancedSearch {...searchProps} />
              </div>
              {this.showTable()}
            </div>
            {this.state.visible && this.showModal()}
          </div>
        }
      />
    );
  }
}
